package com.tlgen.coopera.controller;

import com.tlgen.coopera.annotation.Refresh;
import com.tlgen.coopera.config.disconf.YmlPropertySourceFactory;
import com.tlgen.coopera.model.Coopera;
import com.tlgen.coopera.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.Objects;

import static com.tlgen.coopera.constant.Constants.READ_FILE_PATH;
import static com.tlgen.coopera.utils.FileUtils.createFile;

@Refresh
@RestController
@RequestMapping("/speed/coopera")
public class CooperaController {

    @Autowired
    private ConfigurableEnvironment environment;

    @PostMapping(value = "/publish", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public String publish(@RequestBody Coopera coopera) {
        createFile(coopera.getContent());
        PropertySource<?> propertySource = YmlPropertySourceFactory.loadProfiles();
        if (Objects.nonNull(propertySource)) {
            environment.getPropertySources().addLast(propertySource);
        }
        return "SUCCESS";
    }

    @GetMapping("/readFile")
    public String readFile() {
        return FileUtils.readFile(new File(READ_FILE_PATH));
    }

}
